<template>
  <el-dialog :title="title" :width="width" :visible.sync="showMapComponent" top="10vh" custom-class="baidu-map"
    @close="cancel" v-if="showMapComponent" append-to-body>
    <baidu-map :style="mapStyle" :center="center" :zoom="zoom" :scroll-wheel-zoom="true" @click="getClickInfo"
      @moving="syncCenterAndZoom" @moveend="syncCenterAndZoom" @ready="onBaiduMapReady" @zoomend="syncCenterAndZoom">
      <bm-view style="width: 100%; height: 100%;" />
      <bm-marker :position="{ lng: center.lng, lat: center.lat }" :dragging="true" animation="BMAP_ANIMATION_BOUNCE" />
      <bm-info-window :position="{ lng: center.lng, lat: center.lat }" @close="hideInfo" :show="showInfo">
        <div style="min-width: 100px" class="info">
          <p v-if="pointInfo.name">地点名称：{{ pointInfo.name }}</p>
          <p v-if="pointInfo.address">详细地址：{{ pointInfo.address }}</p>
          <p v-if="pointInfo.location">
            <span style="margin-right: 10px">
              经度：{{ pointInfo.location.lat }}</span>
            <span>
              纬度：{{ pointInfo.location.lng }}
            </span>
          </p>
        </div>
      </bm-info-window>
      <bm-city-list anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-city-list>
      <bm-control :offset="{ width: '10px', height: '10px' }">
        <bm-auto-complete v-model="keyword" :sug-style="{ zIndex: 999999 }">
          <el-input v-model="keyword" type="text" placeholder="请输入地名关键字" clearable>
            <i slot="prefix" class="el-input__icon el-icon-search" />
          </el-input>
        </bm-auto-complete>
      </bm-control>
      <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_LEFT" show-address-bar auto-location />
      <bm-local-search :keyword="keyword" :auto-viewport="true" :panel="false" />
    </baidu-map>
    <span slot="footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { BaiduMap, BmControl, BmView, BmAutoComplete, BmLocalSearch, BmMarker, BmGeolocation } from 'vue-baidu-map'
export default {
  components: {
    BaiduMap,
    BmControl,
    BmView,
    BmAutoComplete,
    BmLocalSearch,
    BmMarker,
    BmGeolocation
  },
  props: {
    // 在子组件中使用 props 选项去接收来自父组件传递过来的数据
    mapHeight: {
      type: Number,
      default: 500
    },
    title: {
      type: String,
      default: '门店定位'
    },
    width: {
      type: [Number, String],
      default: '70%'
    },
    height: {
      type: [Number, String],
      default: '80%'
    },
  },
  data () {
    return {
      BMap: null, // 地图组件是否就绪
      map: null,
      point: "",
      showMapComponent: false,
      keyword: '', // 地区搜索的信息
      mapStyle: {
        width: '100%',
        height: this.mapHeight + 'px'
      },
      // 点信息
      pointInfo: {},
      showInfo: false,
      region: "",
      // 当前行政区划
      center: { lng: 104.07274727, lat: 30.57899372 },
      choosedLocation: "",
      zoom: 15
    }
  },
  methods: {
    choose (region, val) {
      this.region = region;
      this.point = val.position;
      this.choosedLocation = val.address;
      this.showMapComponent = true;
    },
    // ready事件：在你需要二次开发或手动控制其子组件，可以使用在此事件中使用返回的 BMap 类和 map 实例进行手动控制
    onBaiduMapReady (e) {
      console.log('返回BMap类和map实例', e)
      const that = this
      this.BMap = e.BMap
      this.map = e.map
      if (this.BMap) {
        if (this.point) {
          console.log(this.point);
          let points = this.point.split(",");
          that.center = { lng: points[0], lat: points[1] };
          // that.pointInfo.location = that.center
          // that.pointInfo.address = that.choosedLocation
          // that.showInfo = true
        } else {
          if (that.region) {
            const geoCoder = new this.BMap.Geocoder()
            geoCoder.getPoint(that.region, function (point) {
              if (point) {
                that.map.centerAndZoom(point, 15);
              }
            });
          }
        }

        // const geolocation = new this.BMap.Geolocation()
        // 通过 getCurrentPosition() 方法：获取当前的位置信息
        // geolocation.getCurrentPosition(res => {
        //   console.log('返回详细地址和经纬度', res)
        //   const { lng, lat } = res.point
        //   const { province, city, district, street, street_number } = res.address

        //   that.center = { lng, lat }
        //   that.choosedLocation = { province, city, district, addr: street + street_number, lng, lat }
        // })
      }
    },

    /** *
     * 地图点击事件。
     */
    getClickInfo (e) {
      // 调整地图中心位置
      this.center.lng = e.point.lng
      this.center.lat = e.point.lat

      // 此时已经可以获取到BMap类
      if (this.BMap) {
        const that = this
        // Geocoder() 类进行地址解析
        // 创建地址解析器的实例
        const geoCoder = new this.BMap.Geocoder()
        // getLocation() 类--利用坐标获取地址的详细信息
        // getPoint() 类--获取位置对应的坐标
        geoCoder.getLocation(e.point, function (res) {
          console.log('获取经纬度', e.point, '获取详细地址', res)
          const addrComponent = res.addressComponents
          const surroundingPois = res.surroundingPois
          const province = addrComponent.province
          const city = addrComponent.city
          const district = addrComponent.district
          let addr = addrComponent.street
          if (surroundingPois.length > 0 && surroundingPois[0].title) {
            if (addr) {
              addr += `-${surroundingPois[0].title}`
            } else {
              addr += `${surroundingPois[0].title}`
            }
          } else {
            addr += addrComponent.streetNumber
          }
          that.choosedLocation = province + city + district + addr
          that.pointInfo.location = e.point
          that.pointInfo.address = that.choosedLocation
          that.showInfo = true
        })
      }
    },
    syncCenterAndZoom (e) {
      // 返回地图当前的缩放级别
      this.zoom = e.target.getZoom()
    },
    hideInfo () {
      this.showInfo = false
    },
    /** *
     * 确认
     */
    confirm () {
      this.showMapComponent = false
      this.$emit('ok', this.center, this.choosedLocation)
    },
    /** *
     * 取消
     */
    cancel () {
      this.showMapComponent = false
    }
  }
}
</script>

<style lang="scss">
.baidu-map {
  .el-dialog__body {
    padding: 5px !important;
  }
}

.info {
  color: grey;
  font-size: 12px;
}
</style>